package com.warm.mini.wework.controller;

import com.alibaba.fastjson.JSON;
import com.warm.mini.wework.form.ConfigForm;
import com.warm.mini.wework.form.PosterForm;
import com.warm.mini.wework.form.PosterOption;
import com.warm.mini.wework.model.JsonConfig;
import com.warm.mini.wework.model.JsonConfig.Poster;
import com.warm.mini.wework.util.ImageUtil;
import com.warm.mini.wework.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.File;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.UUID;

/**
 * @author warmchuang
 * @date 2023/12/6 10:47
 * @desc
 */
@Controller
//@RequestMapping(value = "/poster")
@Slf4j
public class ThymeleafController {

    public static JsonConfig jsonConfig;

    private static final String JSON_CONFIG_PATH = "config.json";

    public static JsonConfig getConfig(){
        if(jsonConfig == null){
            jsonConfig = JsonUtil.readJsonFile(JSON_CONFIG_PATH, JsonConfig.class);
        }
        return jsonConfig;
    }

    public static void refreshConfig(){
        jsonConfig = JsonUtil.readJsonFile(JSON_CONFIG_PATH, JsonConfig.class);
    }
    @GetMapping("/json-form")
    public String showJsonForm(Model model) {
        ConfigForm configForm = new ConfigForm();
        configForm.setJsonStr(JSON.toJSONString(getConfig()));
        model.addAttribute("configForm", configForm);
        return "json-form";
    }

    @PostMapping("/submit")
    public String submitJsonForm(@ModelAttribute("configForm") ConfigForm configForm, BindingResult result) {
        JsonUtil.writeJsonFile(JSON_CONFIG_PATH, JSON.parseObject(configForm.getJsonStr()));
        refreshConfig();
        return "redirect:/json-form";
    }


    @GetMapping("/poster")
    public String showUploadPage(Model model) {
        JsonConfig config = getConfig();
        List<PosterOption> options = new ArrayList<>();
        config.getPosters().forEach(p -> {
            PosterOption option = new PosterOption();
            option.setType(p.getType());
            option.setName(p.getName());
            option.setSourceImg(p.getSourceImg());
            if(p.getType().equals(9999)){ // 倒计时逻辑
                int dayOfMonth = LocalDate.now().getMonth().maxLength() - LocalDate.now().getDayOfMonth();
                LocalDate.now().getMonth().getValue();
                option.setName(String.format(option.getName(), dayOfMonth));
                option.setSourceImg(String.format(option.getSourceImg(), dayOfMonth));
            }
            // 页面路径处理 多个 static 路径访问不到
            option.setSourceImg(option.getSourceImg().replace("static", ""));
            options.add(option);
        });
        model.addAttribute("posterForm", new PosterForm());
        model.addAttribute("options", options);
        return "poster";
    }

    @PostMapping("/poster")
    public String uploadFile(@ModelAttribute("posterForm") PosterForm posterForm, RedirectAttributes redirectAttributes) {
        try{
            JsonConfig config = getConfig();
            Poster poster = config.getPosterMap().get(posterForm.getType());

            byte[] bytes = ImageUtil.addWatermark(posterForm.getFile().getInputStream(), poster);

            String filename = "/temp/" + UUID.randomUUID() + ".png";

            ImageUtil.addWatermark(posterForm.getFile().getInputStream(), poster, filename);
            //redirectAttributes.addFlashAttribute("imageBase64", Base64.getEncoder().encodeToString(bytes));
            //redirectAttributes.addFlashAttribute("image", "/temp/" + filename);
            return filename;
        } catch (Exception e){
            e.printStackTrace();
        }
        return "poster";
    }

    @GetMapping("/display")
    public String displayImage(@ModelAttribute("image") String image) {
        return "display";
    }

    /*@PostMapping("/poster")
    public ResponseEntity<byte[]> uploadFile(@ModelAttribute("posterForm") PosterForm posterForm, BindingResult result) {
        try{
            JsonConfig config = getConfig();
            Poster poster = config.getPosterMap().get(posterForm.getType());

            byte[] bytes = ImageUtil.addWatermark(posterForm.getFile().getInputStream(), poster);

            // 构建ResponseEntity对象，设置Content-Type和Content-Disposition等响应头信息
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_PNG);
            headers.setContentDispositionFormData("attachment", posterForm.getType() + "-" + System.currentTimeMillis() + ".png");
            ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, HttpStatus.OK);
            return responseEntity;
        } catch (Exception e){

        }
        return null;
    }*/
}
